#pragma  warning(disable: 4482)


#include <QtCore/QCoreApplication>
#include "qstring.h"
#include <QFile>
#include <QTextStream>
#include <QXmlStreamWriter>
#include "../miniTLN/csvline.h"
#include "../src/corelib/xml/qxmlstream.h"
#include <QDateTime>
#include "../ntreco/utils.h"
 

struct Config {
	bool skiptitle;
	QString ifile;
	Config() {
		skiptitle=false;
		ifile="";
	}
}cfg;

void usage() {
	fputs("Usage:\n"
		"\t tln2xml [-h] <input_tln> \n"
		"\t -h : input file has header line \n"
		,stderr);
	exit(1);
}

void setConfig(int argc,char**argv) 
{
	for(int i = 1;i<argc;i++)
		if (strcmp(argv[i],"-h")==0)
			cfg.skiptitle=true;
		else if (strcmp(argv[i],"-")==0) {
			fprintf(stderr,"bad argument : %s",argv[i]);
			exit(1);
		} else cfg.ifile=argv[i];
	if (cfg.ifile.isEmpty())
		usage();
}




int main(int argc, char *argv[])
{
	QCoreApplication a(argc, argv);
	setConfig(argc,argv);
	QFile file(cfg.ifile);
	if (!file.open(QIODevice::ReadOnly)) {
		perror("error reading input file");
		exit(1);
	}
	QTextStream is(&file);
	if (cfg.skiptitle)
		is.readLine();
	QFile output;
	output.open(stdout,QIODevice::WriteOnly);
	QXmlStreamWriter stream(&output);
	stream.setAutoFormatting(true);
	
	stream.writeStartElement("data");//<data>
	stream.writeAttribute("date-time-format","iso8601");
	while (true) {
		QString line = is.readLine();
		if (line.isEmpty())
			break;
		CSVLine csvline(line);
		QDateTime time = toDateTime(csvline[TIME]);
		QString action = csvline[ACTION];
		QString target = csvline[TARGET];
		QString src = csvline[SRC];
		QString host = csvline[HOST];
		if (!time.isValid()) 
				continue;
		stream.writeStartElement("event");
		stream.writeAttribute("start",time.toString("yyyy-MM-ddThh:mm:ss")+".000");
		//stream.writeAttribute("trackNum",QString::number(time.time().second()));
		//stream.writeAttribute("start"," May 11 2001 00:00:00 GMT-0600");
		stream.writeAttribute("title",src+"@"+host+","+action+":"+target);
		stream.writeCharacters(csvline[SRC]+"@"+csvline[HOST]+"["+csvline[SRC]+"]\n"+
			((csvline[TAMPER]).isEmpty()?"":"Tamper:"+csvline[TAMPER])+"\n"+
			"misc:"+csvline[MISC]
			);
		stream.writeEndElement();

	}
	stream.writeEndElement(); // </data>
	
	return 0;
}
